﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Ruandao.MiniFace
{
    public abstract class ListWidgetBase : WidgetBase
    {
        /// <summary>
        /// 记录分组显示的数量，分了组之后，每组的第一个记录可以用GroupFirstItemTemplate来定制显示方式。
        /// </summary>
        public int GroupNumber { get; set; }
        public string IdName { get; set; }
        public string CurrentId { get; set; }

        public ListWidgetBase()
        {
            this.GroupNumber = 1;  //取值为1表示不分组。
        }

        public override void Render( TemplateContext templateContext, System.IO.TextWriter writer)
        {
            dynamic dataList;
            var vars = VariablesToPython(templateContext, out dataList);
            for (int i = 0; i < vars.Count; i++)
            {
                templateContext.PythonScope.SetVariable(vars[i].Key, vars[i].Value);
            }

            RenderDataList(templateContext, writer, dataList);

            for (int i = vars.Count - 1; i >= 0; i--)
            {
                templateContext.PythonScope.RemoveVariable(vars[i].Key);
            }
        }

        private void RenderDataList(TemplateContext templateContext, System.IO.TextWriter writer, dynamic dataList)
        {
            if (dataList == null || dataList.Count == 0)
            {
                foreach (var sub in this.WidgetTemplate.TemplateItems["EmptyTemplate"])
                {
                    sub.Render(templateContext, writer);
                }
                return;
            }

            foreach (var content in this.WidgetTemplate.Contents)
            {
                var template = content as TemplateItem;
                if (template == null)
                {
                    content.Render(templateContext, writer);
                    continue;
                }

                // 渲染子模板。
                switch (template.ItemName)
                {
                    case "ItemTemplate":
                        int itemCounter = 0;
                        foreach (var item in dataList)
                        {
                            itemCounter++;
                            templateContext.PythonScope.SetVariable("ItemCounter", itemCounter);
                            templateContext.PythonScope.SetVariable("Item", item);

                            // 交替项（偶数项）模板
                            string templateName = "ItemTemplate";
                            if (itemCounter % 2 == 0 &&
                                this.WidgetTemplate.TemplateItems.ContainsKey("AlternateItemTemplate"))
                            {
                                templateName = "AlternateItemTemplate";
                            }

                            // 每一组的起始项模板
                            if (itemCounter % this.GroupNumber == 1 &&
                                this.WidgetTemplate.TemplateItems.ContainsKey("GroupFirstItemTemplate"))
                            {
                                templateName = "GroupFirstItemTemplate";
                            }

                            // 起始项模板
                            if (itemCounter == 1 &&
                                this.WidgetTemplate.TemplateItems.ContainsKey("FirstItemTemplate"))
                            {
                                templateName = "FirstItemTemplate";
                            }

                            // 当前项模板
                            if (!string.IsNullOrWhiteSpace(this.IdName) && !string.IsNullOrWhiteSpace(this.CurrentId))
                            {
                                PropertyInfo propertyInfo = item.GetType().GetProperty(this.IdName);
                                string id = (propertyInfo == null) ? "" : propertyInfo.GetValue(item, null).ToString();
                                if (id == this.CurrentId &&
                                    this.WidgetTemplate.TemplateItems.ContainsKey("CurrentItemTemplate"))
                                {
                                    templateName = "CurrentItemTemplate";
                                }
                            }

                            var contents = this.WidgetTemplate.TemplateItems[templateName];

                            foreach (var sub in this.WidgetTemplate.TemplateItems[templateName])
                            {
                                sub.Render(templateContext, writer);
                            }

                            if (this.WidgetTemplate.TemplateItems.ContainsKey("SeparatorTemplate") &&
                                    itemCounter < dataList.Count)
                            {
                                var separators = this.WidgetTemplate.TemplateItems["SeparatorTemplate"];
                                foreach (var s in separators) s.Render(templateContext, writer);
                            }

                            templateContext.PythonScope.RemoveVariable("Item");
                            templateContext.PythonScope.RemoveVariable("ItemCounter");
                        }
                        break;
                    default:
                        throw new Exception("在ContentListWidget中不支持子模板：" + template.ItemName + "。");
                }
            }
        }

        /// <summary>
        /// 获取暴露给Python脚本的所有对象的集合，Value为所暴露的对象，对应的Key为在Python中引用该对象的变量名。
        /// </summary>
        /// <param name="templateContext"></param>
        /// <param name="dataList">输出参数，所要呈现的对象集合。</param>
        /// <returns></returns>
        protected abstract List<KeyValuePair<string, dynamic>> VariablesToPython(TemplateContext templateContext, out dynamic dataList);
    }
}
